﻿function getPoll(qId) {
    var param = "operation=getpoll&qid=" + qId;
    doRequest(param, onGetPoll, Error);
}

function onGetPoll(data) {
    data = json_eval(data);
    if (data !== undefined) {
        for (var id in data) {
            if (data[id][3] !== null) {
                var pollDiv = document.createElement("div");
                pollDiv.id = id;
                pollDiv.setAttribute("class", "poll-form post");

                $("#poll-form-container").append(pollDiv);

                $("#" + id).append(DrawVotedPoll(id, data[id]));
                animateResults();
            }
            else {
                $("#poll-form-container").append(DrawPoll(id, data[id]));
            }
        }
    } else {
        $.jGrowl("Не удалось получить опрос", { life: 2000, theme: 'error' });
    }
}

function getPolls() {
    var param = "operation=getpolls";
    doRequest(param, onGetPolls, Error);
}

function onGetPolls(data) {
    data = json_eval(data);
    
    if (data !== undefined) {
        for (var id in data) {
            if (data[id][3] !== null) {
                var pollDiv = document.createElement("div");
                pollDiv.id = id;
                pollDiv.setAttribute("class", "poll-form post");

                $("#poll-form-container").append(pollDiv);

                $("#" + id).append(DrawVotedPoll(id, data[id]));
                animateResults();
            }
            else {
                $("#poll-form-container").append(DrawPoll(id, data[id]));
            }
        }
    } else {
        $.jGrowl("Вы еще не создавали опросы", { life: 2000, theme: 'info' });
    }
}

function getMyPolls() {
    var param = "operation=getmypolls";
    doRequest(param, onGetMyPolls, Error);
}

function onGetMyPolls(data) {
    data = json_eval(data);

    if (data !== undefined) {
        for (var id in data) {
            if (data[id][3] !== null) {
                var pollDiv = document.createElement("div");
                pollDiv.id = id;
                pollDiv.setAttribute("class", "poll-form post");

                $("#poll-form-container").append(pollDiv);

                $("#" + id).append(DrawVotedPoll(id, data[id]));
                animateResults();
            }
            else {
                $("#poll-form-container").append(DrawPoll(id, data[id]));
            }
        }
    } else {
        $.jGrowl("Вы еще не создавали опросы", { life: 2000, theme: 'info' });
    }
}

function getMyVotes() {
    var param = "operation=getmyvotes";
    doRequest(param, onGetMyPolls, Error);
}

function DrawPoll(id, data) {
    var pollDiv = document.createElement("div");
    pollDiv.id = id;
    pollDiv.setAttribute("class", "poll-form post");

    var qp = document.createElement("a");
    qp.setAttribute("class", "qTitle");
    qp.setAttribute("href", "?poll=" + id);
    var qTitle = document.createTextNode(data[0]);
    qp.appendChild(qTitle);
    pollDiv.appendChild(qp);
    var questions = data[4];

    var date = document.createElement("div");
    date.setAttribute("class", "pollDate");
    if (data[1] != "") {
        var qDate = document.createTextNode("Дата окончания: " + data[1]);
    } else {
        var qDate = document.createTextNode("Дата окончания: не определена.");
    }
    date.appendChild(qDate);
    pollDiv.appendChild(date);
    
    var ap = document.createElement("div");
    ap.setAttribute("class", "entry");
    
    for (var aid in questions) {
        var qAnswer = document.createElement("input");
        qAnswer.type = "radio";
        qAnswer.name = "poll";
        qAnswer.id = aid;
        ap.appendChild(qAnswer);

        var aLabel = document.createElement('label');
        var aLabelText = document.createTextNode(questions[aid][0]);
        aLabel.appendChild(aLabelText);
        aLabel.setAttribute("for", aid);
        
        ap.appendChild(aLabel);
        var br = document.createElement('br');
        ap.appendChild(br);
    }
    var summ = document.createElement("div");
    summ.setAttribute("class", "summ");
    
    var qSubmit = document.createElement("input");
    qSubmit.type = "button";
    qSubmit.value = "Голосовать";
    qSubmit.setAttribute("class", "poll-form-btn");
    qSubmit.setAttribute("onClick", "formProcess('" + pollDiv.id + "')");

    summ.appendChild(qSubmit);

    var tags = document.createElement("div");
    tags.setAttribute("class", "pollTags");
    
    if (data[2] != "") {
        

        var tTags = document.createTextNode("Тэги: ");
        tags.appendChild(tTags);
        
        var arr = data[2].split(';');
        for (var i = 0; i < arr.length; i++) {
            var aTags = document.createElement("a");
            aTags.setAttribute("href", "/?tag=" + arr[i]);
            var qTags = document.createTextNode(arr[i]);
            aTags.appendChild(qTags);
            tags.appendChild(aTags);
        }
        summ.appendChild(tags);
    }
    else {
        var tTags = document.createTextNode(" ");
        tags.appendChild(tTags);
        summ.appendChild(tags);
    }

    ap.appendChild(summ);
    ap.appendChild(addSocialSharingBlock(pollDiv.id, data[0]));
    pollDiv.appendChild(ap);
    return pollDiv;
}

function DrawVotedPoll(id, data) {
    var total_votes = 0;
    var percent;

    var questions = data[4];

    for (var aid in questions) {
        total_votes = total_votes + parseInt(questions[aid][1]);
    }
    
    var pollDiv = document.createElement("div");
    pollDiv.id = "result_" + id;
    pollDiv.setAttribute("class", "poll-results");

    var pollTitle = document.createElement("a");
    pollTitle.setAttribute("href", "/?poll=" + id);
    pollTitle.setAttribute("class", "qTitle");

    var qTitleText = document.createTextNode(data[0]);
    pollTitle.appendChild(qTitleText);
    pollDiv.appendChild(pollTitle);

    var date = document.createElement("div");
    date.setAttribute("class", "pollDate");
    if (data[1] != "") {
        var qDate = document.createTextNode("Дата окончания: " + data[1]);
    } else {
        var qDate = document.createTextNode("Дата окончания: не определена.");
    }
    date.appendChild(qDate);
    pollDiv.appendChild(date);

    //pollDiv.appendChild(addSocialSharingBlock(id, data[0]));

    var ap = document.createElement("div");
    ap.setAttribute("class", "entry");
    
    var pollDl = document.createElement("dl");
    pollDl.setAttribute("class", "graph");

    for (var aid in questions) {
        percent = Math.round((parseInt(questions[aid][1]) / parseInt(total_votes)) * 100);
        
        var pollDt = document.createElement("dt");
        pollDt.setAttribute("class", "bar-title");

        var pollDtText = document.createTextNode(questions[aid][0]);
        pollDt.appendChild(pollDtText);

        var pollDd = document.createElement("dd");
        pollDd.setAttribute("class", "bar-container");

        var pollDdDiv = document.createElement("div");
        pollDdDiv.setAttribute("class", "bar-line");
        pollDdDiv.id = "bar" + aid;
        
        if (aid !== data[3]) {
            pollDdDiv.setAttribute("style", "width:0%;");
        }
        else {
            pollDdDiv.setAttribute("style", "width:0%;background-color:#0066cc;");
        }

        var pollDdDivTxt = document.createTextNode(" ");
        pollDdDiv.appendChild(pollDdDivTxt);
        pollDd.appendChild(pollDdDiv);
        
        var pollDdStrong = document.createElement("strong");
        var pollDdStrongTxt = document.createTextNode(percent + "%");
        pollDdStrong.appendChild(pollDdStrongTxt);
        pollDd.appendChild(pollDdStrong);

        pollDl.appendChild(pollDt);
        pollDl.appendChild(pollDd);
    }

    ap.appendChild(pollDl);

    var summ = document.createElement("div");
    summ.setAttribute("class", "summ");
    
    var sumP = document.createElement("div");
    sumP.setAttribute("class", "totalVoted");

    var sumTxt = document.createTextNode("Всего голосов: " + total_votes);
    sumP.appendChild(sumTxt);

    summ.appendChild(sumP);
    
    var tags = document.createElement("div");
    tags.setAttribute("class", "pollTags");
    
    if (data[2] != "") {
        var tTags = document.createTextNode("Тэги: ");
        tags.appendChild(tTags);

        var arr = data[2].split(';');
        for (var i = 0; i < arr.length; i++) {
            var aTags = document.createElement("a");
            aTags.setAttribute("href", "/?tag=" + arr[i]);
            var qTags = document.createTextNode(arr[i]);
            aTags.appendChild(qTags);
            
            tags.appendChild(aTags);
        }
        summ.appendChild(tags);
    }
    else {
        var tTags = document.createTextNode(" ");
        tags.appendChild(tTags);
        summ.appendChild(tags);
    }
    
    
    ap.appendChild(summ);

    ap.appendChild(addSocialSharingBlock(id, data[0]));
    
    pollDiv.appendChild(ap);

    return pollDiv;
}

function addPoll() {
    var param = "operation=addpoll";
    param += "&qtitle=" + $("#qid").val();
    param += "&enddate=" + $("#inputDate").val();
    
    var n = 1;
    $("#answers input.c-input").each(function () {
        if ($('#' + $(this).attr("id")).val() !== undefined && $.trim($('#' + $(this).attr("id")).val()).length != 0) {
            param += "&a" + n + "=" + $('#' + $(this).attr("id")).val();
            n++;
        } else {
            //console.log($('#' + $(this).attr("id")).val() + " is empty");
        }
    });

    param += "&n=" + (n -1);

    var tags = "";
    $("#tags_tagsinput span.tag span").each(function () {
        if ($(this)[0].textContent.trim() !== undefined && $.trim($(this)[0].textContent.trim()).length != 0 && validateTxt($(this)[0].textContent.trim())) {
            tags += $(this)[0].textContent.trim() +";";
        } else {
        }
    });

    param += "&tags=" + tags;
    
    if (validateAddPoll()) {
        doRequest(param, onAddPoll, Error);
    } else {
        $.jGrowl("Опрос составлен не корректно", { life: 2000, theme: 'warn' });
    }
}

function onAddPoll(data) {
    
    $.fancybox.close();

    data = json_eval(data);
    if (data !== undefined) {
        $.jGrowl("Опрос создан", { life: 2000, theme: 'info' });

        for (id in data) {
            $("#poll-form-container").prepend(DrawPoll(id, data[id]));
        }
    }
    getTags();
}


function searchPolls() {
    var param = "operation=search&key=" + $("#search-text").val();
    doRequest(param, onGetSearch, Error);
}

function onGetSearch(data) {
    data = json_eval(data);
    if (data !== undefined) {
        $("#poll-form-container").empty();
        for (var id in data) {
            if (data[id][3] !== null) {
                var pollDiv = document.createElement("div");
                pollDiv.id = id;
                pollDiv.setAttribute("class", "poll-form post");

                $("#poll-form-container").append(pollDiv);

                $("#" + id).append(DrawVotedPoll(id, data[id]));
                animateResults();
            }
            else {
                $("#poll-form-container").append(DrawPoll(id, data[id]));
            }
        }
    } else {
        $.jGrowl("По Вашему запросу ничего не найдено", { life: 2000, theme: 'warn' });
    }
}

var counter = 3;
var limit = 8;

function addInput(divName) {
    if (counter == limit) {
        $.jGrowl("Максимальное количество ответов для вопроса " + counter, { life: 2000, theme: 'info' });
    }
    else {
        var newdiv = document.createElement('div');
        newdiv.setAttribute("class", "answer");
        var x = counter + 1;
        //  " <label for='ans" + x + "'>" + x + ") </label>
        newdiv.innerHTML = "<input type='text' id='ans" + x + "'class='c-input' name='myInputs[]'>";
        document.getElementById(divName).appendChild(newdiv);
        counter++;
        AddPollCenter();

        if  ($("#answers input.c-input").length == limit) {
            $("#addAnswerBtn").hide();
        }
    }
}

function AddPollCenter() {
    $.fancybox.center();
}

function gol_logout() {
    $.cookie('token', null);
    window.location = "/";
}

function delete_cookie(cookie_name) {
    var cookie_date = new Date();
    cookie_date.setTime(cookie_date.getTime() - 1);
    document.cookie = cookie_name += "=; expires=" + cookie_date.toGMTString();
}

function getTags(tag) {
    if (tag !== undefined) {
        var params = "operation=getbytag&tag=" + tag;
        doRequest(params, onGetPolls, Error);
    }
    else {
        var params = "operation=gettags";
        doRequest(params, OnGetTagsSuccess, Error);
    }
}

function OnGetTagsSuccess(data) {
    data = json_eval(data);
    if (data !== undefined) {
        $("#tagList").empty();
        for (var id in data) {
            $("#tagList").append('<a href="/?tag=' + id + '">'+id+'</a> ');
        }
    }
}


/*** AUTH ***/

function VKauthInfo(data) {
    if (data.session) {
        var params = "operation=login&net=vk&uid=" + data.session.user["id"] + "&hash=" + data.session.sig + "&first_name=" + data.session.user["first_name"] + "&last_name=" + data.session.user["last_name"];
        doRequest(params, OnVkLoginSuccess, Error);
    } else {
        $.jGrowl("Не удалось выполнить аутентификацию ВКонтакте", { life: 2000, theme: 'error' });
    }
}

function AttachVK(data) {
    if (data.session) {
        var params = "operation=attachuser&net=vk&uid=" + data.session.user["id"] + "&hash=" + data.session.sig;//  + "&first_name=" + data.session.user["first_name"] + "&last_name=" + data.session.user["last_name"];
        doRequest(params, OnAttachVKSuccess, Error);
    } else {
        $.jGrowl("Не удалось выполнить аутентификацию ВКонтакте", { life: 2000, theme: 'error' });
    }
}

function AttachFB() {
    FB.login(function (response) {
        if (response.authResponse) {
            FB.api('/me', function (data) {
                var params = "operation=attachuser&net=fb&uid=" + data.id;// +"&first_name=" + data.first_name + "&last_name=" + data.last_name;
                doRequest(params, OnAttachFbSuccess, Error);
            });
        } else {
            $.jGrowl("Не удалось выполнить аутентификацию Facebook", { life: 2000, theme: 'error' });
        }
    }, { scope: 'email' });
}

//function AttachTW() {
//    twttr.anywhere(function (T) {
//        T.signIn();
//        
//        T.bind("authComplete", function (e, user) {
//            var params = "operation=attachuser&net=tw&uid=" + user["id"];// +"&name=" + user["name"];
//            doRequest(params, OnAttachTwSuccess, Error);
//        });

//        T.bind("signOut", function (e) {
//            $.jGrowl("Не удалось выполнить аутентификацию Twitter", { life: 2000, theme: 'error' });
//        });
//    });
//}

function OnAttachTwSuccess() {
    $.jGrowl("Attach TW succcess", { life: 2000, theme: 'info' });
}

function OnAttachFbSuccess(data) {
    $.jGrowl("Attach FB succcess", { life: 2000, theme: 'info' });
}

function OnAttachVKSuccess(data) {
    $.jGrowl("Attach VK succcess", { life: 2000, theme: 'info' });
}

function OnVkLoginSuccess(data) {
    window.location = "/";
}

function OnFbLoginSuccess(data) {
    window.location = "/";
}

function OnTwLoginSuccess(data) {
    window.location = "/";
}

function OnMailRuLoginSuccess(data) {
    //window.location = "/";
}

var OPT_ID = 0;
var OPT_TITLE = 1;
var OPT_VOTES = 2;

function formProcess(qId) {
    if ($.cookie('token')) {
        //event.preventDefault();
        if ($("#" + qId + " input[@name='poll']:checked").length < 1) {
            $.jGrowl("Вы не выбрали вариант ответа", { life: 2000, theme: 'warn' });
        } else {
            var id = $("#" + qId + " input[@name='poll']:checked").attr("id");

            $("#" + qId).fadeOut("slow", function () {
                var param = "operation=vote&qid=" + qId + "&aid=" + id;
                doRequest(param, onVoted, Error);
            });
        }
    }
    else {
        $.jGrowl("Для участия в голосовании Вам необходимо Войти", { life: 3000, theme: 'warn' });
    }
    
}

function onVoted(data) {
    data = json_eval(data);
    if (data !== undefined) {
        for (id in data) {
            $("#" + id).empty();
            $("#" + id).append(DrawVotedPoll(id, data[id]));
            //$("#poll-form-container").append(DrawVotedPoll(id, data[id]));
            $("#" + id).fadeIn("slow", function() {
                animateResults();
            });

            //    $("#" + pollDiv1.id).prepend(pollDiv).fadeIn("slow", function () {
            //        animateResults();
            //    });
            
        }
        $.jGrowl("Ваш голос принят", { life: 2000, theme: 'info' });
    }
}

function animateResults() {
    $(".poll-results div.bar-line").each(function () {
        var percentage = $(this).next().text();
        $(this).css({ width: "0%" }).animate({
            width: percentage
        }, 'slow');
    });
}

function onBitLy(data) {
    //console.log(data);
}


var api_key = "",
api_login = "",
api_url = "http://api.bit.ly/v3/shorten";

function addSocialSharingBlock(qid, title) {
    //var shortUrl = bit_url();


//    var login = "golosim";
//    var api_key = "R_bd4517c9a2e4ba60f2e0354d507e95c7";

//    get_short_url("http://golosim.ru/?poll=" + qid, login, api_key, function (short_url) {
//        console.log(short_url);
//    });

    
    
    var ShareDiv = document.createElement("div");
    ShareDiv.id = "sharingDiv";
    ShareDiv.setAttribute("class", "sharingDiv");

    var linkTxt = document.createTextNode(title);

    var vkShare = document.createElement("div");
    vkShare.setAttribute("class", "vk-share");
    
    var vkShareA = document.createElement("a");
    vkShareA.setAttribute("href", "http://vk.com/share.php?url=http://golosim.ru/?poll=" + qid + "&title=" + title + "&image=http://golosim.ru/golosim.png");
    vkShareA.setAttribute("target", "_blank");
    vkShareA.setAttribute("title", "Опубликовать во ВКонтакте");
    vkShareA.appendChild(vkShare);

    var twShare = document.createElement("div");
    twShare.setAttribute("class", "tw-share");
    var twShareA = document.createElement("a");
    twShareA.setAttribute("href", "http://twitter.com/intent/tweet?url=http://golosim.ru/?poll=" + qid + "&text=" + title + "&hashtags=golosim");
    twShareA.setAttribute("target", "_blank");
    twShareA.setAttribute("title", "Опубликовать в Twitter");
    twShareA.appendChild(twShare);


    var fbShare = document.createElement("div");
    fbShare.setAttribute("class", "fb-share");
    var fbShareA = document.createElement("a");
    fbShareA.setAttribute("href", "http://www.facebook.com/sharer.php?u=http://golosim.ru/?poll=" + qid + "&t=" + title + "&src=sp");
    fbShareA.setAttribute("target", "_blank");
    fbShareA.setAttribute("title", "Опубликовать в Facebook");
    fbShareA.appendChild(fbShare);

    /*var glShare = document.createElement("div");
    glShare.setAttribute("class", "gl-share");
    var glShareA = document.createElement("a");
    glShareA.setAttribute("href", "http://m.google.com/app/plus/x/?v=compose&hideloc=1&content=*${title}*%0A_from%20${source}_%0A%0A${body}%0A%0Aисточник%3A%20${short-url}" + qid + "&t=" + title);
    glShareA.setAttribute("target", "_blank");
    glShareA.setAttribute("title", "Опубликовать в Google+");
    glShareA.appendChild(glShare);*/

    ShareDiv.appendChild(vkShareA);
    ShareDiv.appendChild(twShareA);
    ShareDiv.appendChild(fbShareA);
    //ShareDiv.appendChild(glShare);

    return ShareDiv;
}


/*** VALIDATORS ***/

function validateAddPoll() {
    console.log(validateQuestion());
    console.log(validateQuestionDate());
    console.log(validate2Answers());
   if (validateQuestion() && validateQuestionDate() && validate2Answers()) {
       return true;
   }
    else {
       return false;
   }
}

function validateQuestion() {
    var str = $("#qid").val();
    if (str != "") {
        if (validateTxt(str)) {
            return true;
        } else {
            $.jGrowl("Введены некорректные символы в теме вопроса", { life: 2000, theme: 'warn' });
            return false;
        }
    } else {
        $.jGrowl("Вы не указали вопрос", { life: 2000, theme: 'warn' });
        return false;
    }
}

function validateQuestionDate() {
    var value = $("#inputDate").val();
    try {
        if (value != "") {
            if ($("#inputDate").val().match(/^(?:(0[1-9]|[12][0-9]|3[01])[\- \/.](0[1-9]|1[012])[\- \/.](19|20)[0-9]{2})$/)) {
                var DayIndex = 0;
                var MonthIndex = 1;
                var YearIndex = 2;

                value = value.replace("-", "/").replace(".", "/");
                var SplitValue = value.split("/");
                var OK = true;
                if (!(SplitValue[DayIndex].length == 1 || SplitValue[DayIndex].length == 2)) {
                    OK = false;
                }
                if (OK && !(SplitValue[MonthIndex].length == 1 || SplitValue[MonthIndex].length == 2)) {
                    OK = false;
                }
                if (OK && SplitValue[YearIndex].length != 4) {
                    OK = false;
                }
                if (OK) {
                    var Day = parseInt(SplitValue[DayIndex], 10);
                    var Month = parseInt(SplitValue[MonthIndex], 10);
                    var Year = parseInt(SplitValue[YearIndex], 10);

                    if (OK = ((Year > new Date().getFullYear()) && (Year <= 2099))) {
                        return OK;
                    }
                    if (OK = ((Year = new Date().getFullYear()) && (Year <= 2099))) {
                        if (OK = ((Month <= 12 && Month > 0) && (Month > new Date().getMonth() + 1))) {
                            return OK;
                        }
                        else if (Month = new Date().getMonth() + 1) {
                            if (Day > new Date().getDate()) {
                                return true;
                            } else {
                                $.jGrowl("Указанная дата должна быть больше текущей даты", { life: 2000, theme: 'warn' });
                            }
                        } else {
                            $.jGrowl("Указанная дата должна быть больше текущей даты", { life: 2000, theme: 'warn' });
                        }
                    } else {
                        $.jGrowl("Указанная дата должна быть больше текущей даты", { life: 2000, theme: 'warn' });
                    }
                }
                if (OK = false) {
                    $.jGrowl("Вы указали некорректную дату", { life: 2000, theme: 'warn' });
                }
                return OK;
            }
            else {
                $.jGrowl("Вы указали некорректную дату", { life: 2000, theme: 'warn' });
            }
        }
        else {
            return true;
        }
    }
    catch (e) {
        return false;
    }
}



function validate2Answers() {
    if ($('#answers input.c-input[value != ""]').length < 2) {
        $.jGrowl("Должно быть больше одного вариантов ответов", { life: 2000, theme: 'warn' });
        return false;
    } else {
        var is = false;
        $('#answers input.c-input[value != ""]').each(function () {
            var str = $('#' + $(this).attr("id")).val();
            if (str != "") {
                if (validateTxt(str)) {
                    is = true;
                } else {
                    $.jGrowl("Введены некорректные символы в одном из ответов", { life: 2000, theme: 'warn' });
                    is = false;
                }
            } else {
                $.jGrowl("Один из ответов пустой", { life: 2000, theme: 'warn' });
                is = false;
            }
        });
        return is;
    }
}

function validateEmail() {
    var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
    if (document.myform.email1.value.search(emailRegEx) == -1) {
        $.jGrowl("Вы указали некорректный email", { life: 2000, theme: 'warn' });
    }
    else {
        return true;
    }
}

function validateTxt(string) {
    if (/^[a-zA-Z0-9а-яА-Я?!@#-=+ :.][^'"/&\\*]+$/.test(string)) {
        return true;
    }
    return false;
}

/*** SYSTEM ***/

function markActiveLink() {
    var path = location.pathname;
    var home = "/";
    var home2 = "/default.aspx";
    $("#menu li a[href='" + [path || home || home2] + "']").each(function () {
        $(this.parentNode).addClass("active");
    });
}

function getQueryString() {
    var result = {}, queryString = location.search.substring(1),
      re = /([^&=]+)=([^&]*)/g, m;

    while (m = re.exec(queryString)) {
        result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
    }

    return result;
}

function doRequest(params, func, errFunc) {
    $.ajax({
        type: "GET",
        url: "/Handler.ashx",
        error: function (xhr, ajaxOptions, thrownError) { Error(xhr, ajaxOptions, thrownError); },
        data: params,
        success: func,
        cache: false
    });
}

function Error(xhr, ajaxOptions, thrownError) {
    //console.log("Error.");
    $.jGrowl("Error: " + thrownError, { life: 2000, theme: 'error' });
}

function json_eval(data) {
    if (data != "") {
        data = eval("(" + data + ")");
        for (id in data) {
            if (id == "success") {
                $.jGrowl(data[id], { life: 2000, theme: 'info' });
                return null;
            } else if (id == "warn") {
                $.jGrowl(data[id], { life: 2000, theme: 'warn' });
                return null;
            } else if (id == "error") {
                $.jGrowl(data[id], { life: 2000, theme: 'error' });
                return null;
            } else {
                return data;
            }
        }
    }
    else {
        return null;
    }
}

function bit_url(url) {
    var username = "golosim";
    var key = "R_bd4517c9a2e4ba60f2e0354d507e95c7";
    $.ajax({
        url: "http://api.bit.ly/v3/shorten",
        data: { longUrl: url, apiKey: key, login: username },
        dataType: "jsonp",
        success: function (v) {
            var bit_url = v.data.url;
            return bit_url;
        }
    });

}


function get_short_url(long_url, login, api_key, func) {
    $.getJSON(
        "http://api.bitly.com/v3/shorten?callback=?",
        {
            "format": "json",
            "apiKey": api_key,
            "login": login,
            "longUrl": long_url
        },
        function (response) {
            func(response.data.url);
        }
    );
}



//$("#short").click(function() {
//    var url = $("#url").val();
//    var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig ;
//    var urltest = urlRegex.test(url);
//    if (urltest) {
//        bit_url(url);
//    } else {
//        alert("Bad URL");
//    }
//});


function UpdateUser() {
    $("#ShareVK").val();
    $("#ShareFb").val();
    $("#ShareTW").val();

    $("#UserEmail").val();

}


function setOrCreateMetaTag(metaName, name, value) {
    var t = 'meta[' + metaName + '=' + name + ']';
    var mt = $(t);
    if (mt.length === 0) {
        t = '<meta ' + metaName + '="' + name + '" />';
        mt = $(t).appendTo('head');
    }
    mt.attr('content', value);
}
